import 'dart:typed_data';

import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:jydoctorflutter/utils/tools/toast.dart';
import 'package:pdf_to_image_converter/pdf_to_image_converter.dart';
import 'package:permission_handler/permission_handler.dart';


import '../../generated/l10n.dart';

class InvoiceImageConvertUtil {
  static Future<void> pdfToImageConverterAndSaveToAlbum(String pdfPath) async {
    final PdfImageConverter converter = PdfImageConverter();
    Uint8List? image;
    // 打开 PDF 文件
    await converter.openPdf(pdfPath);
    // 获取 PDF 页数
    final pageCount = converter.pageCount;
    await converter.openPdf(pdfPath);
    // 遍历每一页
    for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
      try {
        // 渲染页面为图像
        Uint8List? image = await converter.renderPage(pageIndex);

        // 如果成功渲染图像，保存该图像到图库
        if (image != null) {
          bool pageSaved = await saveImageToGallery(image, pageIndex);
          Toast.showToast('保存到相册');
        } else {
          Toast.showToast(
            "${pageIndex}th image save failed ${'保存失败'}",
          );
        }
      } catch (e) {
        Toast.showToast('请等待');
        print('Error rendering page $pageIndex: $e');
      }
    }
  }

  /// 保存图像到相册
  static Future<bool> saveImageToGallery(
    Uint8List imageBytes,
    int pageNumber,
  ) async {
    // 请求存储权限
    var status = await Permission.storage.request();
    if (status.isGranted) {
      final result = await ImageGallerySaver.saveImage(
        imageBytes,
        name: "converted_pdf_page_$pageNumber",
        quality: 100,
      );
      return result["isSuccess"] == true;
    } else {
      print("Storage permission denied.");
      return false;
    }
  }
}
